package com.example.admin.mqtt;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.aip.asrwakeup3.core.mini.ActivityMiniRecog;
import com.baidu.speech.EventManagerFactory;

import org.eclipse.paho.client.mqttv3.MqttException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


public class MainActivity extends ActivityMiniRecog {
    protected int led_flag = 1;
    protected int door_flag = 1;
    private ImageView light_control;
    private ImageView door_control;
    private ImageView air_control;
    private ImageView curtain_control;
    private ImageView tv_control;
    private ImageView water_control;
    private TextView text_temperature;
    private TextView text_light;
    private TextView text_door_lock;
    private ImageView about;
    private Intent Tvgo, Doorgo, Airgo,Ledgo,door_lock;
    public static mqtt_tool mqtt = new mqtt_tool();
    public static GetMessage getMessage = new GetMessage();
    private WebView temp_web;
    private WebView bright_web;
    private WebView hum_web;
    private Button vocal_home;


    @SuppressLint({"HandlerLeak", "ClickableViewAccessibility"})

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        temp_web = (WebView) findViewById(R.id.temp_web);
        temp_web.getSettings().setAllowFileAccess(true);
        temp_web.getSettings().setJavaScriptEnabled(true);
        hum_web = (WebView) findViewById(R.id.hum_web);
        hum_web.getSettings().setAllowFileAccess(true);
        hum_web.getSettings().setJavaScriptEnabled(true);
        vocal_home = findViewById(R.id.vocal_home);
        getMessage.setTemperture("0");
        getMessage.setLight("0");
        getMessage.setHum("0");
        getMessage.setDoor_msg(" ");
        // 设置允许JS弹窗
        temp_web.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        hum_web.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        bright_web = (WebView) findViewById(R.id.bright_web);
        bright_web.getSettings().setAllowFileAccess(true);
        bright_web.getSettings().setJavaScriptEnabled(true);

        // 设置允许JS弹窗
        bright_web.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);

        temp_web.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        bright_web.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        hum_web.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);

        temp_web.setInitialScale(250);//为25%，最小缩放等级
        bright_web.setInitialScale(250);//为25%，最小缩放等级
        hum_web.setInitialScale(250);//为25%，最小缩放等级
        // chartshow_web.loadUrl("file:android_asset/echarts.html");
        WebViewUtil.setWebView(temp_web, "file:android_asset/echarts.html");
        WebViewUtil.setWebView(hum_web, "file:android_asset/echarts2.html");
        WebViewUtil.setWebView(bright_web, "file:android_asset/echarts3.html");
        /**
         * js方法的调用必须在html页面加载完成之后才能调用。
         * 用webview加载html还是需要耗时间的，必须等待加载完，在执行代用js方法的代码。
         */
        door_control=findViewById(R.id.door_control);
        door_control.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               /* if(door_flag == 0)
                {
                    publishmessageplus(mqtt_pub_topic,"{\"doorLock\":\"open\",\"led\":\"\"}");
                    Toast.makeText(MainActivity.this,"开门" ,Toast.LENGTH_SHORT).show();
                    door_flag =1;
                }else{
                    publishmessageplus(mqtt_pub_topic,"{\"doorLock\":\"close\",\"led\":\"\"}");
                    Toast.makeText(MainActivity.this,"关门" ,Toast.LENGTH_SHORT).show();
                    door_flag =0;
                }*/
                door_lock = new Intent(MainActivity.this, DoorActivity.class);
                startActivity(door_lock);
            }
        });
        curtain_control = findViewById(R.id.curtain_control);
        curtain_control.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               /* if(door_flag == 0)
                {
                    publishmessageplus(mqtt_pub_topic,"{\"doorLock\":\"open\",\"led\":\"\"}");
                    Toast.makeText(MainActivity.this,"开门" ,Toast.LENGTH_SHORT).show();
                    door_flag =1;
                }else{
                    publishmessageplus(mqtt_pub_topic,"{\"doorLock\":\"close\",\"led\":\"\"}");
                    Toast.makeText(MainActivity.this,"关门" ,Toast.LENGTH_SHORT).show();
                    door_flag =0;
                }*/
                Doorgo = new Intent(MainActivity.this, CurtainActivity.class);
                startActivity(Doorgo);
            }
        });
        about = findViewById(R.id.about);
        about.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               /* Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://182.254.214.196:1880/ui/#!/0?socketid=hUYU61bMg-9uc8TAAAAm"));
                startActivity(intent);*/
                Intent intent= new Intent(MainActivity.this, Esp32cam_Activity.class);
                startActivity(intent);
            }
        });
        tv_control = findViewById(R.id.tv_control);
        tv_control.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               /* if(door_flag == 0)
                {
                    publishmessageplus(mqtt_pub_topic,"{\"doorLock\":\"open\",\"led\":\"\"}");
                    Toast.makeText(MainActivity.this,"开门" ,Toast.LENGTH_SHORT).show();
                    door_flag =1;
                }else{
                    publishmessageplus(mqtt_pub_topic,"{\"doorLock\":\"close\",\"led\":\"\"}");
                    Toast.makeText(MainActivity.this,"关门" ,Toast.LENGTH_SHORT).show();
                    door_flag =0;
                }*/
                Tvgo = new Intent(MainActivity.this, TvActivity.class);
                startActivity(Tvgo);
            }
        });
        air_control = findViewById(R.id.air_control);
        air_control.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               /* if(door_flag == 0)
                {
                    publishmessageplus(mqtt_pub_topic,"{\"doorLock\":\"open\",\"led\":\"\"}");
                    Toast.makeText(MainActivity.this,"开门" ,Toast.LENGTH_SHORT).show();
                    door_flag =1;
                }else{
                    publishmessageplus(mqtt_pub_topic,"{\"doorLock\":\"close\",\"led\":\"\"}");
                    Toast.makeText(MainActivity.this,"关门" ,Toast.LENGTH_SHORT).show();
                    door_flag =0;
                }*/
                Airgo = new Intent(MainActivity.this, AirActivity.class);
                startActivity(Airgo);
            }
        });
        light_control = findViewById(R.id.light_control);
        light_control.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Ledgo = new Intent(MainActivity.this, LedActivity.class);
                startActivity(Ledgo);
            }
        });
        //  两个控件联动  num  按钮单机 更改 textview 的内容
        // 基于sdk集成1.1 初始化EventManager对象
        initPermission();
        asr = EventManagerFactory.create(this, "asr");
        // 基于sdk集成1.3 注册自己的输出事件类
        asr.registerListener(this); //  EventListener 中 onEvent方法
        /*btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                start();
            }
        });*/
        vocal_home.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    //更改为按下时
                    start();
                    // Toast.makeText(ActivityMiniRecog.this, "我正在听", Toast.LENGTH_LONG).show();
                    vocal_home.setBackgroundResource(R.drawable.shape2);
                    vocal_home.setText("正在识别（识别完成后再次点击发送）");
                } else if (event.getAction() == MotionEvent.ACTION_UP) {
                    //改为抬起时的图片
                    vocal_home.setBackgroundResource(R.drawable.shape3);
                    vocal_home.setText("按下说话");
                    stop();
                    //Toast.makeText(ActivityMiniRecog.this, "", Toast.LENGTH_LONG).show();
                    //  Toast.makeText(MainActivity.this, "松开：" + final_result, Toast.LENGTH_SHORT).show();
                    // mqtt.publishmessageplus("curtain_control", final_result);

                  /*  if (final_result.equals("打开窗帘。"))
                        mqtt.publishmessageplus("curtain_control", "{\"power\":\"right\"}");
                    else if (final_result.equals("关闭窗帘。"))
                        mqtt.publishmessageplus("curtain_control", "{\"power\":\"left\"}");
                    else if (final_result.equals("暂停。"))
                        mqtt.publishmessageplus("curtain_control", "{\"power\":\"off\"}");
*/
                }

                return false;

            }

        });
        handler_vocal=new Handler(){
            @SuppressLint("SetTextI18n")
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case 1: //开机校验更新回传
                        Log.v("handler_vocal", msg.obj.toString());
                        if (msg.obj.equals("打开窗帘。"))
                            mqtt.publishmessageplus("curtain_control", "{\"power\":\"right\"}");
                        else if (msg.obj.equals("关闭窗帘。"))
                            mqtt.publishmessageplus("curtain_control", "{\"power\":\"left\"}");
                        else if (msg.obj.equals("暂停。"))
                            mqtt.publishmessageplus("curtain_control", "{\"power\":\"off\"}");
                        break;
                }
                }
        };
//**********************************************************//
        mqtt.Mqtt_init();
        mqtt.startReconnect();
        mqtt.handler = new Handler() {
            @SuppressLint("SetTextI18n")
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case 1: //开机校验更新回传
                        break;
                    case 2:  // 反馈回传
                       /* if(message.toString().contains("door_msg")) {
                            msg.what = 1;   //收到消息标志位
                            msg.obj = message.toString();
                            //发送messge到handler
                            door_handler.sendMessage(msg);    // hander 回传
                        }*/
                        break;
                    case 3:  //MQTT 主页消息处理   收到消息回传   UTF8Buffer msg=new UTF8Buffer(object.toString());
                        //处理message 传过来的 obj字段（里面包了数据）
                        try {
                            Log.v("1", msg.obj.toString());
                            if(msg.obj.toString().toString().contains("door_msg")) {
                                Message msg2=new Message();
                                msg2.what = 1;   //收到消息标志位
                                msg2.obj = msg.obj.toString().toString();
                                //发送messge到handler
                                mqtt.door_handler.sendMessage(msg2);    // hander 回传
                            }else {

                                JSONObject jsonObject = new JSONObject(msg.obj.toString());
                                if (jsonObject.getString("temperature") != null)
                                    getMessage.setTemperture(jsonObject.getString("temperature"));
                                if (jsonObject.getString("bright") != null)
                                    getMessage.setLight(jsonObject.getString("bright"));
                                if (jsonObject.getString("hum") != null)
                                    getMessage.setHum(jsonObject.getString("hum"));

                                temp_web.post(new Runnable() {
                                    @TargetApi(Build.VERSION_CODES.KITKAT)

                                    @Override
                                    public void run() {
                                        // 注意调用的JS方法名要对应上
                                        // 调用javascript的callJS()方法
                                        temp_web.evaluateJavascript("returnResult(" + Double.parseDouble(getMessage.getTemperture()) + ")", null);
                                        // chartshow_web.loadUrl("echarts:returnResult(" + 69 + ")");
                                        //chartshow_web.loadUrl("file:android_asset/echarts.html:callJS()");
                                    }
                                });
                                bright_web.post(new Runnable() {
                                    @TargetApi(Build.VERSION_CODES.KITKAT)

                                    @Override
                                    public void run() {
                                        // 注意调用的JS方法名要对应上
                                        // 调用javascript的callJS()方法
                                        bright_web.evaluateJavascript("returnResult(" + Double.parseDouble(getMessage.getLight()) * 0.01 + ")", null);
                                        // chartshow_web.loadUrl("echarts:returnResult(" + 69 + ")");
                                        //chartshow_web.loadUrl("file:android_asset/echarts.html:callJS()");
                                    }
                                });
                                hum_web.post(new Runnable() {
                                    @TargetApi(Build.VERSION_CODES.KITKAT)

                                    @Override
                                    public void run() {
                                        // 注意调用的JS方法名要对应上
                                        // 调用javascript的callJS()方法
                                        hum_web.evaluateJavascript("returnResult(" + Double.parseDouble(getMessage.getHum()) + ")", null);
                                        // chartshow_web.loadUrl("echarts:returnResult(" + 69 + ")");
                                        //chartshow_web.loadUrl("file:android_asset/echarts.html:callJS()");
                                    }
                                });
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        break;
                    case 4://收到窗帘界面的信息

                        break;

                    case 30:  //连接失败
                        Toast.makeText(MainActivity.this, "连接失败", Toast.LENGTH_SHORT).show();

                        break;
                    case 31:   //连接成功
                        Toast.makeText(MainActivity.this, "连接成功", Toast.LENGTH_SHORT).show();
                        try {
                            mqtt.client.subscribe(mqtt.mqtt_sub_topic, 1);
                        } catch (MqttException e) {
                            e.printStackTrace();
                        }
                        break;
                    default:
                        break;
                }
            }
        };
    }

    private void parseEasyJson(String json) {

        try {
            JSONArray jsonArray = new JSONArray(json);
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = (JSONObject) jsonArray.get(i);
                GetMessage getMessage = new GetMessage();
                getMessage.setTemperture(jsonObject.getString("temperature"));
                getMessage.setLight(jsonObject.getString("bright"));
                getMessage.setHum(jsonObject.getString("doorLock"));

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static class WebViewUtil {

        /**
         * 给webview添加数据
         *
         * @param webView
         * @param url
         */
        public static void setWebView(WebView webView, String url) {
            //如果访问的页面中要与Javascript交互，则webview必须设置支持Javascript
            webView.getSettings().setJavaScriptEnabled(true);
//        webView.getSettings().setDomStorageEnabled(true);

            webView.loadUrl(url);
            webView.setWebViewClient(new WebViewClient());
            webView.clearCache(true);
            webView.setWebChromeClient(new WebChromeClient());
            //缓存模式如下：
            //LOAD_CACHE_ONLY: 不使用网络，只读取本地缓存数据
            //LOAD_DEFAULT: （默认）根据cache-control决定是否从网络上取数据。
            //LOAD_NO_CACHE: 不使用缓存，只从网络获取数据.
            //LOAD_CACHE_ELSE_NETWORK，只要本地有，无论是否过期，或者no-cache，都使用缓存中的数据。
            //不使用缓存,只从网络获取数据。
            webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
//        webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        }
    }
}

